<template>
  <div class="home-container">
    <!-- 头部导航 -->
    <header class="header">
      <div class="header-content">
        <div class="logo-section">
          <span class="logo-icon">🏠</span>
          <h1>Flask JWT 认证系统</h1>
        </div>
        <div class="user-section">
          <span class="welcome">👋 欢迎, {{ username }}</span>
          <button class="logout-btn" @click="handleLogout">🚪 退出登录</button>
        </div>
      </div>
    </header>

    <!-- 主内容区 -->
    <main class="main-content">
      <div class="content-wrapper">
        
        <!-- 用户信息卡片 -->
        <div class="card user-info-card">
          <h2>👤 用户信息</h2>
          <div v-if="userInfo" class="info-grid">
            <div class="info-item">
              <span class="label">用户ID:</span>
              <span class="value">{{ userInfo.user_id }}</span>
            </div>
            <div class="info-item">
              <span class="label">用户名:</span>
              <span class="value">{{ userInfo.username }}</span>
            </div>
            <div class="info-item">
              <span class="label">登录状态:</span>
              <span class="value status-active">✅ 已认证</span>
            </div>
          </div>
          <button class="refresh-btn" @click="getUserInfo" :disabled="loading">
            {{ loading ? '⏳ 加载中...' : '🔄 刷新用户信息' }}
          </button>
        </div>

        <!-- Token信息卡片 -->
        <div class="card token-info-card">
          <h2>🔑 Token 信息</h2>
          <div class="token-details">
            <div class="token-item">
              <span class="label">Access Token:</span>
              <div class="token-value">{{ formatToken(accessToken) }}</div>
            </div>
            <div class="token-item">
              <span class="label">Refresh Token:</span>
              <div class="token-value">{{ formatToken(refreshToken) }}</div>
            </div>
          </div>
          <button class="refresh-btn" @click="handleRefreshToken" :disabled="refreshing">
            {{ refreshing ? '⏳ 刷新中...' : '🔄 刷新 Access Token' }}
          </button>
        </div>

        <!-- 订单列表卡片 -->
        <div class="card orders-card">
          <h2>📦 我的订单</h2>
          <div v-if="orders.length > 0" class="orders-list">
            <div v-for="order in orders" :key="order.id" class="order-item">
              <div class="order-info">
                <span class="order-id">订单 #{{ order.id }}</span>
                <span class="order-product">{{ order.product }}</span>
              </div>
              <div class="order-details">
                <span class="order-price">¥{{ order.price }}</span>
                <span :class="['order-status', getStatusClass(order.status)]">
                  {{ order.status }}
                </span>
              </div>
            </div>
          </div>
          <button class="refresh-btn" @click="getOrders" :disabled="loadingOrders">
            {{ loadingOrders ? '⏳ 加载中...' : '🔄 刷新订单列表' }}
          </button>
        </div>

        <!-- 快捷导航卡片 -->
        <div class="card nav-card">
          <h2>🚀 快捷导航</h2>
          <div class="nav-buttons">
            <button class="nav-btn" @click="$router.push('/employee')">
              <span class="nav-icon">👥</span>
              <span class="nav-text">员工管理</span>
            </button>
            <button class="nav-btn" @click="$router.push('/department')">
              <span class="nav-icon">🏢</span>
              <span class="nav-text">部门管理</span>
            </button>
            <button class="nav-btn" @click="$router.push('/leave')">
              <span class="nav-icon">📋</span>
              <span class="nav-text">请假管理</span>
            </button>
          </div>
        </div>

        <!-- 系统信息卡片 -->
        <div class="card system-info-card">
          <h2>📊 系统说明</h2>
          <div class="system-features">
            <div class="feature-item">✅ JWT Token 认证机制</div>
            <div class="feature-item">✅ 自动请求拦截器</div>
            <div class="feature-item">✅ Token 刷新机制</div>
            <div class="feature-item">✅ Redis 黑名单管理</div>
            <div class="feature-item">✅ RBAC权限控制</div>
            <div class="feature-item">✅ 数据库ORM集成</div>
          </div>
        </div>

      </div>
    </main>

    <!-- 消息提示 -->
    <div v-if="message" :class="['toast', messageType]">
      {{ message }}
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import request from '../utils/request.js'

const router = useRouter()

// 状态数据
const username = ref(localStorage.getItem('username') || '未知用户')
const accessToken = ref(localStorage.getItem('access_token') || '')
const refreshToken = ref(localStorage.getItem('refresh_token') || '')
const userInfo = ref(null)
const orders = ref([])
const loading = ref(false)
const loadingOrders = ref(false)
const refreshing = ref(false)
const message = ref('')
const messageType = ref('info')

// 组件挂载时获取数据
onMounted(() => {
  getUserInfo()
  getOrders()
})

// 获取用户信息
const getUserInfo = async () => {
  loading.value = true
  try {
    const response = await request.get('/user/userinfo')
    
    if (response.data.code === 200) {
      userInfo.value = response.data.data
      showToast('用户信息加载成功', 'success')
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    if (error.response?.status === 401) {
      showToast('登录已过期，请重新登录', 'error')
      setTimeout(() => router.push('/'), 1500)
    } else {
      showToast('获取用户信息失败', 'error')
    }
  } finally {
    loading.value = false
  }
}

// 获取订单列表
const getOrders = async () => {
  loadingOrders.value = true
  try {
    const response = await request.get('/orders/list')
    
    if (response.data.code === 200) {
      orders.value = response.data.data.orders
      showToast('订单列表加载成功', 'success')
    }
  } catch (error) {
    console.error('获取订单失败:', error)
    showToast('获取订单失败', 'error')
  } finally {
    loadingOrders.value = false
  }
}

// 刷新Access Token
const handleRefreshToken = async () => {
  refreshing.value = true
  try {
    const response = await request.post('/user/refresh_token', {
      refresh_token: refreshToken.value
    })
    
    if (response.data.code === 200) {
      const newAccessToken = response.data.data.access_token
      localStorage.setItem('access_token', newAccessToken)
      accessToken.value = newAccessToken
      showToast('Access Token 刷新成功', 'success')
    }
  } catch (error) {
    console.error('刷新Token失败:', error)
    showToast('刷新Token失败：' + (error.response?.data?.message || error.message), 'error')
  } finally {
    refreshing.value = false
  }
}

// 退出登录
const handleLogout = async () => {
  if (!confirm('确定要退出登录吗？')) return
  
  try {
    await request.post('/user/logout')
    showToast('退出登录成功', 'success')
  } catch (error) {
    console.error('退出登录失败:', error)
  } finally {
    // 清除本地存储
    localStorage.removeItem('access_token')
    localStorage.removeItem('refresh_token')
    localStorage.removeItem('username')
    
    // 跳转到登录页
    setTimeout(() => router.push('/'), 1000)
  }
}

// 格式化Token显示
const formatToken = (token) => {
  if (!token) return '暂无'
  if (token.length > 50) {
    return token.substring(0, 30) + '...' + token.substring(token.length - 10)
  }
  return token
}

// 获取订单状态样式类
const getStatusClass = (status) => {
  if (status === '已发货') return 'status-shipped'
  if (status === '待发货') return 'status-pending'
  return ''
}

// 显示Toast消息
const showToast = (msg, type = 'info') => {
  message.value = msg
  messageType.value = type
  setTimeout(() => {
    message.value = ''
  }, 3000)
}
</script>

<style scoped>
.home-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}

/* 头部 */
.header {
  background: white;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  padding: 20px 0;
  position: sticky;
  top: 0;
  z-index: 100;
}

.header-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.logo-section {
  display: flex;
  align-items: center;
  gap: 12px;
}

.logo-icon {
  font-size: 32px;
}

.header h1 {
  font-size: 24px;
  color: #333;
  margin: 0;
}

.user-section {
  display: flex;
  align-items: center;
  gap: 20px;
}

.welcome {
  font-size: 16px;
  color: #555;
}

.logout-btn {
  padding: 10px 20px;
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 600;
  transition: transform 0.2s;
}

.logout-btn:hover {
  transform: translateY(-2px);
}

/* 主内容 */
.main-content {
  max-width: 1200px;
  margin: 40px auto;
  padding: 0 20px;
}

.content-wrapper {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 24px;
}

/* 卡片通用样式 */
.card {
  background: white;
  border-radius: 16px;
  padding: 24px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  transition: transform 0.3s;
}

.card:hover {
  transform: translateY(-4px);
}

.card h2 {
  font-size: 20px;
  color: #333;
  margin: 0 0 20px 0;
  padding-bottom: 12px;
  border-bottom: 2px solid #f0f0f0;
}

/* 用户信息卡片 */
.info-grid {
  display: flex;
  flex-direction: column;
  gap: 12px;
  margin-bottom: 20px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  padding: 10px;
  background: #f8f9fa;
  border-radius: 8px;
}

.info-item .label {
  font-weight: 600;
  color: #666;
}

.info-item .value {
  color: #333;
}

.status-active {
  color: #28a745;
  font-weight: 600;
}

/* Token信息卡片 */
.token-details {
  display: flex;
  flex-direction: column;
  gap: 16px;
  margin-bottom: 20px;
}

.token-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.token-item .label {
  font-weight: 600;
  color: #666;
  font-size: 14px;
}

.token-value {
  padding: 10px;
  background: #f8f9fa;
  border-radius: 8px;
  font-family: monospace;
  font-size: 12px;
  word-break: break-all;
  color: #667eea;
}

/* 订单列表 */
.orders-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
  margin-bottom: 20px;
}

.order-item {
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.order-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.order-id {
  font-size: 12px;
  color: #999;
}

.order-product {
  font-weight: 600;
  color: #333;
}

.order-details {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 4px;
}

.order-price {
  font-size: 18px;
  font-weight: 700;
  color: #f5576c;
}

.order-status {
  padding: 4px 12px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 600;
}

.status-shipped {
  background: #d4edda;
  color: #155724;
}

.status-pending {
  background: #fff3cd;
  color: #856404;
}

/* 系统信息 */
.system-features {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
}

.feature-item {
  padding: 12px;
  background: linear-gradient(135deg, #667eea15 0%, #764ba215 100%);
  border-radius: 8px;
  font-size: 14px;
  color: #555;
}

/* 刷新按钮 */
.refresh-btn {
  width: 100%;
  padding: 12px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 600;
  transition: transform 0.2s;
}

.refresh-btn:hover:not(:disabled) {
  transform: translateY(-2px);
}

.refresh-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

/* Toast消息 */
.toast {
  position: fixed;
  top: 80px;
  right: 20px;
  padding: 16px 24px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  animation: slideIn 0.3s ease-out;
  z-index: 1000;
  max-width: 400px;
}

@keyframes slideIn {
  from {
    transform: translateX(400px);
    opacity: 0;
  }
  to {
    transform: translateX(0);
    opacity: 1;
  }
}

.toast.success {
  background: #d4edda;
  color: #155724;
  border: 1px solid #c3e6cb;
}

.toast.error {
  background: #f8d7da;
  color: #721c24;
  border: 1px solid #f5c6cb;
}

.toast.info {
  background: #d1ecf1;
  color: #0c5460;
  border: 1px solid #bee5eb;
}

/* 快捷导航 */
.nav-buttons {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.nav-btn {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 16px;
  background: linear-gradient(135deg, #667eea15 0%, #764ba215 100%);
  border: 2px solid transparent;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.3s;
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.nav-btn:hover {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.nav-icon {
  font-size: 24px;
}

.nav-text {
  flex: 1;
  text-align: left;
}

/* 响应式 */
@media (max-width: 768px) {
  .header-content {
    flex-direction: column;
    gap: 16px;
  }
  
  .system-features {
    grid-template-columns: 1fr;
  }
  
  .content-wrapper {
    grid-template-columns: 1fr;
  }
}
</style>

